import axios from "axios"
import router from "@/router"
import Vue from "vue"
const request = axios.create({
  baseURL: 'http://127.0.0.1:80',
  timeout: 50000
})
let loadingInstance = null
request.interceptors.request.use(config => {
  if (localStorage.getItem('tokenStr')) {
    config.headers.Authorization = localStorage.getItem('tokenStr')
  }
  config.headers["Content-Type"] = 'application/x-www-form-urlencoded'
  loadingInstance = Vue.prototype.$loading({ fullscreen: true })
  return config
})
request.interceptors.response.use(response => {
  loadingInstance.$nextTick(() => {
    loadingInstance.close();
  })
  switch (response.data.status) {
    case 401:
      // 登录失效
      Vue.prototype.$message.error(response.data.message)
      localStorage.removeItem('tokenStr')
      localStorage.removeItem('identity')
      router.push('/login')
      alert('请重新登录！')
      break
    case 404:
      if (response.statusText !== null) {
        Vue.prototype.$message.error(response.statusText)
      } else {
        Vue.prototype.$message.error('未知错误')
      }
      break
    case 500:
      if (response.statusText !== null) {
        Vue.prototype.$message.error(response.statusText)
      } else {
        Vue.prototype.$message.error('未知错误')
      }
      break
    default:
      return response
  }
  return response
})
export default request
